<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="${pageContext.request.contextPath}/lib/static/login/images/favicon.ico">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/layui/css/layui.css" media="all">
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.form.js"></script>
    <script src="${pageContext.request.contextPath}/lib/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>日志管理</legend>
        </fieldset>
    </div>
    <hr class="layui-bg-red">

    <!--按钮及查询框组-->
    <div class="layui-row">
        <div class="layui-col-md-offset1">
            <form class="layui-form">
                <div class="layui-inline" style="text-align: left">
                    <input class="layui-input" name="criteria" autocomplete="off" placeholder="用户名 / 操作 / IP">
                </div>
                <div class="layui-input-inline">
                    <input type="text" id="start_time" name="startTime" autocomplete="off" placeholder="开始时间" class="layui-input">           
                </div>
                <div class="layui-input-inline">
                    <input type="text" id="end_time" name="endTime" autocomplete="off" placeholder="结束时间" class="layui-input">           
                </div>
                <button class="layui-btn layuiadmin-btn-admin" lay-submit="" lay-filter="search">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
            </form>
        </div>
    </div>


    <table class="layui-hide" id="logTable" lay-filter="logMonitor"></table>

    <script type="text/html" id="logToolbar">
        <div class="layui-btn-container">
            <%--<button class="layui-btn layui-btn-sm" lay-event="delByIds">多行删除</button>--%>
            <%--<button class="layui-btn layui-btn-sm" lay-event="add">新增</button>--%>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">查看详情</a>
        <%--<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>--%>
    </script>

    <script>
        var baseUrl = '${pageContext.request.contextPath}/sys/log/';

        /*公用根据id或ids删除用户*/
        function deleteLogByIds($, ids, tableLogIns, len) {
            layer.confirm("您选中了" + len + "条数据，确认删除？", function (index) {
                /*发送ajax请求访问后台*/
                $.post(
                    baseUrl + 'deleteByIds',
                    {ids: ids},
                    function (result) {
                        if (result.code == 0) {
                            layer.msg(result.msg, {icon: 1});
                            /*刷新表格数据*/
                            tableLogIns.reload({
                                url: baseUrl + 'get'
                            });
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    },
                    "json"
                );
            });
        }

        layui.use(['jquery', 'table', 'form'], function () {
            layer = layui.layer;
            var table = layui.table;
            var form = layui.form;
            var tableLogIns = table.render({
                elem: '#logTable'
                , title: '日志数据'
                , toolbar: '#logToolbar'
                , url: baseUrl + 'get'
                /*修改默认向后台传递的页码、大小参数名 @ming*/
                , request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,height: 'full-150'
                , cols: [[{type: 'numbers', title: '序号'}
                    , {field: 'id', title: 'ID', sort: true}
                    , {field: 'username', title: '用户名', sort: true}
                    , {field: 'operation', title: '操作方法', sort: true}
                    , {field: 'method', title: '请求方法', sort: true}
                    , {field: 'params', title: '请求参数', sort: true}
                    , {field: 'ip', title: 'IP地址', sort: true}
                    , {field: 'time', title: '执行时间', sort: true}
                    , {
                        field: 'createdTime',
                        title: '创建时间',
                        sort: true,
                        templet: '<div>{{layui.laytpl.toDateString(d.createdTime)}}</div>',
                        width: 250
                    }
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
                ]]
                , page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    , groups: 5
                }
            });

            //时间戳处理
            layui.laytpl.toDateString = function (d, format) {
                /*当时间为null时返回空字符串*/
                if (!d) {
                    return "";
                }
                var date = new Date(d)
                    , ymd = [
                    this.digit(date.getFullYear(), 4)
                    , this.digit(date.getMonth() + 1)
                    , this.digit(date.getDate())
                ]
                    , hms = [
                    this.digit(date.getHours())
                    , this.digit(date.getMinutes())
                    , this.digit(date.getSeconds())
                ];
                format = format || 'yyyy-MM-dd HH:mm:ss';
                return format.replace(/yyyy/g, ymd[0])
                    .replace(/MM/g, ymd[1])
                    .replace(/dd/g, ymd[2])
                    .replace(/HH/g, hms[0])
                    .replace(/mm/g, hms[1])
                    .replace(/ss/g, hms[2])
            };
            //数字前置补零
            layui.laytpl.digit = function (num, length, end) {
                var str = '';
                num = String(num);
                length = length || 2;
                for (var i = num.length; i < length; i++) {
                    str += '0';
                }
                return num < Math.pow(10, length) ? str + (num | 0) : num;
            };

            //头工具栏事件
            table.on('toolbar(logMonitor)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'delByIds':
                        /*获得要删除的ids*/
                        var data = checkStatus.data;
                        var ids = [];
                        $.each(data, function (index, value) {
                            var id = value.id;
                            ids.push(id);
                        });
                        /*根据id删除数据*/
                        deleteLogByIds($, ids.toString(), tableLogIns, data.length);
                        break;
                    case 'add':
                        layer.open({
                            content: [baseUrl + 'log_edit'],
                            type: 2,
                            title: '<h2>添加日志</h2>',
                            maxmin: true,
                            shadeClose: true, //点击遮罩关闭层
                            offset: '50px',
                            area: ['800px', '530px'],
                            closeBtn: 2,
                            success: function (layero, index) {
                                layer.iframeAuto(index);
                            }
                        });
                        break;
                }
            });

            //监听行工具事件
            table.on('tool(logMonitor)', function (obj) {
                var data = obj.data;
                /*单项删除功能*/
                switch (obj.event) {
                    case 'delByIds':
                        /*根据id删除数据*/
                        deleteLogByIds($, data.id, tableLogIns, 1);
                        break;
                    case 'edit':

                        layer.open({
                            content: [baseUrl + 'log_update'],
                            type: 2,
                            title: '<h2>日志详情</h2>',
                            maxmin: true,
                            shadeClose: true, //点击遮罩关闭层
                            offset: '50px',
                            btn: ['关闭'],
                            area: ['800px', '530px'],
                            success: function (layero, index) {
                                var body = layer.getChildFrame('body', index);
                                // 取到弹出层里的元素，并把编辑的内容放进去
                                body.find('#layui-username').val(data.username).attr("readonly", "");//将选中的数据的id传到编辑页面的隐藏域，便于根据ID修改数据
                                body.find('#layui-operation').val(data.operation).attr("readonly", "");
                                body.find('#layui-method').val(data.method).attr("readonly", "");
                                body.find('#layui-params').val(data.username).attr("readonly", "");
                                body.find('#layui-ip').val(data.ip).attr("readonly", "");
                                body.find('#layui-time').val(data.time).attr("readonly", "");
                                body.find('#layui-createdTime').val(layui.laytpl.toDateString(data.createdTime)).attr("readonly", "");
                                /*时间格式转换*/
                                body.find('#layui-isdel').val(data.isdel).attr("readonly", "");
                            }
                        });

                }
            });
            form.on('submit(search)', function (data) {
                tableLogIns.reload({
                    url: baseUrl + 'get'
                    , method: "post" /*解决参数传递中文乱码*/
                    , where: data.field,
                });
                return false;
            });


        });


        /*时间段查询*/
        layui.use(['laydate'], function () {
            var $ = layui.$;
            var laydate = layui.laydate;
            var nowTime = new Date().valueOf();
            var max = null;

            var start = laydate.render({
                elem: '#start_time',
                type:'datetime',
                format:'yyyy-MM-dd HH:mm:ss',
                max: nowTime,
                done: function(value, date,endDate) {
                    endMax = end.config.max;
                    end.config.min = date; //最大时间为结束时间的开始值  
                    end.config.min.month = date.month - 1;
                    $("#start_time").val(value);
                }
            });

            var end = laydate.render({
                elem: '#end_time',
                type:'datetime',
                format:'yyyy-MM-dd HH:mm:ss',
                max:  4073558400000,
                min:nowTime,
                done: function(value, date){
                    if($.trim(value) == ''){
                        var curDate = new Date();
                        date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                    }
                    start.config.max = date;//最小时间为开始时间的最大值  
                    start.config.max.month = date.month -1;
                    $("#end_time").val(value);
                }
            })

        });


    </script>
</div>
</body>
</html>
